<template>
  <view class="multi-select-wrap">
    <view
      v-for="item in options"
      :key="item.id"
      class="option"
      @click="toggleSelect(item)"
    >
      <!-- 左边勾选图标 -->
      <z-icon
        :name="selectedIds.includes(item.id) ? 'checked' : 'check'"
        size="32rpx"
      ></z-icon>

      <!-- 内容部分 -->
      <view class="option-label">
        <template v-for="(part, i) in parseName(item.name)" :key="i">
          <text v-if="part.type === 'text'" class="fc-dark6">{{ part.value }}</text>
          <input
            v-else
            class="inner-input"
            type="digit"
            :value="getInputValue(item.id, i)"
            placeholder="（请输入）"
            placeholder-class="fc-c5"
            @click.stop
            @input="onInputChange($event, item.id, i)"
          />
        </template>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  /** 选项数组 */
  options: {
    type: Array,
    required: true
  },
  /** 回显数据 [{ id, inputValues: [] }] */
  modelValue: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const selectedIds = ref([])
const inputValues = ref({}) // { id: { index: value } }

/** 分解 name：把所有 x 拆分成文本 + 输入 */
function parseName(name) {
  const parts = []
  const segs = name.split('x')
  for (let i = 0; i < segs.length; i++) {
    if (segs[i]) parts.push({ type: 'text', value: segs[i] })
    if (i < segs.length - 1) parts.push({ type: 'input' })
  }
  return parts
}

/** 初始化 inputValues 结构 */
function initInputValues() {
  const obj = {}
  props.options.forEach(opt => {
    const parts = parseName(opt.name)
    obj[opt.id] = {}
    parts.forEach((p, i) => {
      if (p.type === 'input') obj[opt.id][i] = ''
    })
  })
  inputValues.value = obj
}

/** 获取值 */
function getInputValue(id, index) {
  if (!inputValues.value[id]) inputValues.value[id] = {}
  if (!(index in inputValues.value[id])) inputValues.value[id][index] = ''
  return inputValues.value[id][index]
}

/** 处理输入事件（兼容 UniApp） */
function onInputChange(e, id, index) {
  const val = e.detail?.value ?? e.target?.value ?? ''
  setInputValue(id, index, val)
}

/** 设置值 + 触发更新 */
function setInputValue(id, index, val) {
  if (!inputValues.value[id]) inputValues.value[id] = {}
  inputValues.value[id][index] = val

  // ⚙️ 输入时自动勾选
  if (!selectedIds.value.includes(id)) {
    selectedIds.value.push(id)
  }

  emitChange()
}

/** 多选切换 */
function toggleSelect(item) {
  const i = selectedIds.value.indexOf(item.id)
  if (i > -1) selectedIds.value.splice(i, 1)
  else selectedIds.value.push(item.id)
  emitChange()
}

/** 触发结果输出 */
function emitChange() {
  const result = props.options
    .filter(opt => selectedIds.value.includes(opt.id))
    .map(opt => {
      const parts = parseName(opt.name)
      const group = inputValues.value[opt.id] || {}
      const list = parts
        .map((p, i) => (p.type === 'input' ? group[i] || '' : null))
        .filter(v => v !== null && v.trim() !== '')
      return {
        id: opt.id,
        name: opt.name,
        inputValues: list,
        inputValue: list.join(',')
      }
    })
  emit('update:modelValue', result)
  emit('change', result)
}

/** 🧩 应用回显数据（modelValue） */
function applyModelValue(newVal) {
  if (!Array.isArray(newVal)) return
  selectedIds.value = newVal.map(v => v.id)

  newVal.forEach(item => {
    const opt = props.options.find(o => o.id === item.id)
    if (!opt) return
    const parts = parseName(opt.name)
    const group = {}
    let idx = 0
    parts.forEach((p, i) => {
      if (p.type === 'input') {
        group[i] = item.inputValues?.[idx] || ''
        idx++
      }
    })
    inputValues.value[item.id] = group
  })
}

/** 初始化监听 */
watch(() => props.options, initInputValues, { immediate: true })
watch(() => props.modelValue, applyModelValue, { immediate: true, deep: true })
</script>

<style scoped>
.multi-select-wrap {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}
.option {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 10rpx 20rpx;
  border-radius: 12rpx;
  background-color: #fff;
}
.option-label {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8rpx;
  font-size: 28rpx;
  color: #333;
}
.inner-input {
  width: 25%;
  text-align: center;
  font-size: 28rpx;
}
</style>
